package org.hu.vhr.service;

import org.hu.vhr.mapper.MenuMapper;
import org.hu.vhr.mapper.MenuRoleMapper;
import org.hu.vhr.model.Hr;
import org.hu.vhr.model.Menu;
import org.hu.vhr.model.MenuRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * MenuService
 * @author Sweeney
 */
@Service
public class MenuService {
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    MenuRoleMapper menuRoleMapper;

    /**
     * 通过存放在Spring Security中的用户信息来判断
     * @return List<Menu>
     */
    public List<Menu> getMenusByHrId() {
        return menuMapper.getMenusByHrId(((Hr)SecurityContextHolder
                        .getContext().getAuthentication().getPrincipal()).getId());
    }

//    @Cacheable
    public List<Menu> getAllMenusWithRole(){
        return menuMapper.getAllMenusWithRole();
    }

    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }

    public List<Integer> getMidsByRid(Integer rid) {
        return menuMapper.getMidsByRid(rid);
    }

    @Transactional
    public boolean updateRoles(Integer rid, Integer[] mids) {
        if(mids!=null) {
            menuRoleMapper.deleteByRid(rid);
            Integer result = menuRoleMapper.insertRecord(rid, mids);
            return result == mids.length;
        }
        else{
            menuRoleMapper.deleteByRid(rid);
            return true;
        }
    }
}
